package com.hhsj.dynamicui.server.servlet.admin.consts;

import com.hhsj.androidserver.HttpServlet;
import com.hhsj.androidserver.HttpServletRequest;
import com.hhsj.androidserver.HttpServletResponse;
import com.hhsj.androidserver.WebServlet;
import com.hhsj.dynamicui.model.base.BaseModel;
import com.hhsj.dynamicui.server.DynamicUIService;

import org.json.JSONArray;
import org.json.JSONObject;

import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 在widget_property_const 中添加参数
 */
@WebServlet("/uhomecp-admin/spec_const_add")
public class AddSpecConstsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse rep) throws Exception {
        doPost(req, rep);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse rep) throws Exception {
        //1.解析
        String const_type = URLDecoder.decode(req.getParameterValues("json")[0], "utf-8");

        String widget_code = null;
        String widget_name = null;
        String desc = null;
        List<SpecProperty> specProperties = new ArrayList<>();
        JSONObject jsonObject = new JSONObject(const_type);
        if (jsonObject != null) {
            widget_code = jsonObject.optString("widget_code");
            widget_name = jsonObject.optString("widget_name");
            desc = jsonObject.optString("desc");
            JSONArray array = jsonObject.optJSONArray("key");

            if (array != null && array.length() > 0) {

                for (int i = 0; i < array.length(); i++) {
                    JSONObject object = array.optJSONObject(i);
                    SpecProperty specProperty = SpecProperty.fromJSON(object);
                    specProperties.add(specProperty);
                }
            }
        }

        Connection connection = DynamicUIService.getInstance().getConnection();


        //step 0 , 判断主常量列表中是否有该widget属性，如果没有，添加进去
        insertWidgetCodeToMainConst(connection, widget_code, widget_name, desc);

        //step 1, 判断创建一个特殊属性表
        createTableIfNotExists(connection);
        //step 2, 插入数据
        insertValue(connection, widget_code, specProperties);


        //3.返回响应结果
        rep.print(BaseModel.newEmpty("0", "成功").toJSONString());
    }

    private void insertWidgetCodeToMainConst(Connection connection, String widget_code, String widget_name, String desc) {

        String sql = "SELECT const_code FROM const_type where widget_code=\'" + widget_code + "\'";
        try {
            PreparedStatement statement = connection.prepareStatement(sql);
            ResultSet set = statement.executeQuery();
            boolean contain = false;
            while (set.next()) {
                if (widget_code.equals(set.getString(0))) {
                    contain = true;
                    break;
                }
            }

            if (!contain) {
                String sql2 = "INSERT INTO const_type (const_type,const_code,const_name,const_desc) VALUES (\'widget_layout\',\'" + widget_code +
                        "\',\'" + widget_name +
                        "\')";
                PreparedStatement statement2 = connection.prepareStatement(sql2);
                boolean result = statement2.execute();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    private void insertValue(Connection connection, String widget_code, List<SpecProperty> specProperties) {
/**
 *                  "widget_code varchar(32) not null,\n" +
 *                     "data_type varchar(32) not null,\n" +
 *                     "data_length int default 4,\n" +
 *                     "data_default varchar(32) default '0', \n" +
 *                     "key_name varchar(32) not null,\n" +
 *                     "key_desc varchar(128) not null);";
 */
        StringBuilder builder = new StringBuilder();
        builder.append("INSERT INTO widget_property_const (widget_code,data_type,data_length,data_default,key_name,key_desc) VALUES ");
        for (int i = 0; i < specProperties.size(); i++) {

            SpecProperty specProperty = specProperties.get(i);
            builder.append("(\'").append(widget_code).append("\',")
                    .append("\'").append(specProperty.type).append("\',")
                    .append(specProperty.length)
                    .append("\'").append(specProperty.default_value).append("\',")
                    .append("\'").append(specProperty.key).append("\',")
                    .append("\'").append(specProperty.desc).append("\'")
                    .append("),");

        }

        if (builder.lastIndexOf(",") == builder.length() - 1) {
            builder.deleteCharAt(builder.length() - 1);
        }

        builder.append(");");

        try {
            PreparedStatement statement = connection.prepareStatement(builder.toString());
            statement.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    /**
     * 创建一个视图特殊属性表，如果表存在
     *
     * @param connection
     */
    private void createTableIfNotExists(Connection connection) {

        String queryTableExist = "show tables";
        System.out.println(queryTableExist);
        boolean exists = false;
        try {
            PreparedStatement statement = connection.prepareStatement(queryTableExist);
            ResultSet set = statement.executeQuery();
            while (!exists && set.next()) {
                exists = "widget_property_const".equals(set.getString(0));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        if (!exists) {
            //不存在就创建表
            String sql = "create table widget_property_const (\n" +
                    "    const_id int(8) primary key auto_increment,\n" +
                    "widget_code varchar(32) not null,\n" +
                    "data_type varchar(32) not null,\n" +
                    "data_length int default 4,\n" +
                    "data_default varchar(32) default '0', \n" +
                    "key_name varchar(32) not null,\n" +
                    "key_desc varchar(128) not null);";
            try {
                PreparedStatement statement = connection.prepareStatement(sql);
                boolean success = statement.execute();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

    private static class SpecProperty {
        static final String TYPE_INT = "int";
        static final String TYPE_STRING = "string";

        String key;
        String desc;
        String type;
        int length = 4;
        String default_value = "4";

        public static SpecProperty fromJSON(JSONObject object) {
            if (object == null) {
                return null;
            }
            SpecProperty specProperty = new SpecProperty();
            specProperty.key = object.optString("key_name");//key
            specProperty.type = object.optString("key_type");//值的类型
            specProperty.length = object.optInt("value_length");
            specProperty.default_value = object.optString("value_default", specProperty.default_value);
            specProperty.desc = object.optString("desc", "");
            return specProperty;
        }

        String toSql() {
            return key + getTypeString(type) + " (" + length + ") default " + getDefaultValue(type, default_value);
        }

        private String getTypeString(String type) {
            if ("int".equals(type)) {
                return "int";
            } else {
                return "varchar";
            }
        }

        private String getDefaultValue(String type, String default_value) {
            String defaultStr = null;
            if ("int".equals(type)) {
                defaultStr = default_value;
            } else {
                defaultStr = "\'" + default_value + "\'";
            }
            return defaultStr;
        }
    }

}
